package cn.turboinfo.dongying.api.gateway.admin.controller;

import cn.turboinfo.dongying.api.domain.util.DateTimeFormatHelper;
import cn.turboinfo.dongying.api.domain.util.UrlUtils;
import cn.turboinfo.dongying.api.domain.web.component.file.FileAttachmentHelper;
import cn.turboinfo.dongying.api.entity.common.enumeration.common.EntityObjectType;
import cn.turboinfo.dongying.api.entity.common.pojo.division.Division;
import cn.turboinfo.dongying.api.entity.common.pojo.file.FileAttachment;
import cn.turboinfo.dongying.api.entity.common.pojo.user.UserTypeRel;
import cn.turboinfo.dongying.api.gateway.admin.framework.http.fo.LimitFO;
import cn.turboinfo.dongying.api.gateway.admin.framework.http.fo.LimitFO;
import cn.turboinfo.dongying.api.provider.admin.component.session.AdminSessionHelper;
import cn.turboinfo.dongying.api.provider.admin.framework.shiro.session.AdminSession;
import lombok.val;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLConnection;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gadzs
 * @description Controlller父类
 * @date 2023/2/16 18:44
 */
@RestController
public class BaseController {

    @Autowired
    FileAttachmentHelper fileAttachmentHelper;

    @Autowired
    AdminSessionHelper sessionHelper;


    /**
     * 组装日期查询
     */
    protected void makeBetweenDate(QRequest qRequest, String fieldName, LocalDate stateDate, LocalDate endDate) {
        LocalDateTime stateTime = DateTimeFormatHelper.getStartTime(stateDate);
        LocalDateTime endTime = DateTimeFormatHelper.getEndTime(endDate);
        if (stateTime != null && endTime != null) {
            qRequest.filterBetween(fieldName, stateTime, endTime);
        } else if (stateTime != null && endTime == null) {
            qRequest.filterGreaterEqual(fieldName, stateTime);
        } else if (stateTime == null && endTime != null) {
            qRequest.filterLessEqual(fieldName, endTime);
        }
    }

    /**
     * 组装日期查询
     */
    protected void makeBetweenDateTime(QRequest qRequest, String fieldName, LocalDateTime stateTime, LocalDateTime endTime) {
        if (stateTime != null && endTime != null) {
            qRequest.filterBetween(fieldName, stateTime, endTime);
        } else if (stateTime != null && endTime == null) {
            qRequest.filterGreaterEqual(fieldName, endTime);
        } else if (stateTime == null && endTime != null) {
            qRequest.filterLessEqual(fieldName, endTime);
        }
    }


    /**
     * 查看图片
     *
     * @param fileAttachment
     * @param response
     * @throws IOException
     */
    protected void viewAttachmentImage(FileAttachment fileAttachment, HttpServletResponse response) throws IOException {
        File file = fileAttachmentHelper.readFileAttachment(fileAttachment);
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            response.setContentType(URLConnection.guessContentTypeFromName(file.getName()));
            IOUtils.copy(is, os);
            os.flush();
        }
    }


    /**
     * 查看图片
     *
     * @param fileAttachmentId
     * @param response
     * @throws IOException
     */
    protected void viewAttachmentImage(Long fileAttachmentId, HttpServletResponse response) throws IOException {
        File file = fileAttachmentHelper.readFileAttachment(fileAttachmentId);
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            response.setContentType(URLConnection.guessContentTypeFromName(file.getName()));
            IOUtils.copy(is, os);
            os.flush();
        }
    }

    /**
     * 下载
     *
     * @param fileAttachment
     * @param response
     * @throws IOException
     */
    protected void downloadAttachment(FileAttachment fileAttachment, HttpServletResponse response) throws IOException {
        File file = fileAttachmentHelper.readFileAttachment(fileAttachment);
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            response.setContentType(URLConnection.guessContentTypeFromName(file.getName()));
            response.setHeader("Content-Disposition", "attachment; filename=" + UrlUtils.encodeURIComponent(fileAttachment.getDisplayName()));
            IOUtils.copy(is, os);
            os.flush();
        }
    }


    /**
     * 检查前端查询分页数过大问题
     *
     * @param limitFO
     */
    protected void checkLimit(LimitFO limitFO) {
        int page = limitFO.getPage();
        int limit = limitFO.getLimit();
        limitFO.setPage(page == 0 ? 1 : page);
        limitFO.setLimit(limit == 0 ? 10 : limit);
        if (limit > 50) {
            throw new RuntimeException("分页数过大，请重试");
        }
    }

    /**
     * 获取当前用户的用户类型关系
     *
     * @return
     */
    protected List<UserTypeRel> getUserTypeRelList() {
        return getSession().getUserTypeRelList();
    }

    /**
     * @param entityObjectType
     * @return
     */
    protected List<UserTypeRel> getUserTypeRelList(EntityObjectType entityObjectType) {
        return getSession().getUserTypeRelList().stream().filter(userTypeRel ->
                userTypeRel.getObjectType().equals(entityObjectType)).collect(Collectors.toList());
    }

    protected List<Long> getUserTypeRelIds(EntityObjectType entityObjectType) {
        return getSession().getUserTypeRelList().stream().filter(userTypeRel ->
                userTypeRel.getObjectType().equals(entityObjectType)).map(UserTypeRel::getObjectId).collect(Collectors.toList());
    }

    protected void makeRequestAreaParam(QRequest request) {
        final val communutyRelList = getUserTypeRelList(EntityObjectType.COMMUNITY);
        if (communutyRelList != null && communutyRelList.size() != 0) {
            request.filterEqual("id", communutyRelList.get(0).getObjectId());
        } else {
            final val userTypeRelList = getUserTypeRelList(EntityObjectType.DIVISION);
            request.filterIn("areaCode", userTypeRelList.stream().map(UserTypeRel::getObjectId).collect(Collectors.toList()));
        }
    }

    /**
     * 获取当前用户的关联地区
     *
     * @param divisionList
     * @return
     */
    protected List<Division> getCurrentUserDivision(List<Division> divisionList) {
        AdminSession adminSession = getSession();
        if (adminSession != null) {
            final val userTypeRelList = getUserTypeRelList(EntityObjectType.DIVISION);
            if (userTypeRelList != null && userTypeRelList.size() > 0) {
                //userTypeRelList获取object的set集合
                final val longSet = userTypeRelList.stream().map(UserTypeRel::getObjectId).collect(Collectors.toSet());
                return divisionList.stream().filter(division -> longSet.contains(division.getId())).collect(Collectors.toList());
            }
        }
        return divisionList;
    }

    /**
     * 获取session
     *
     * @return
     */
    protected AdminSession getSession() {
        return sessionHelper.getSession();
    }

}
